﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace MainClient
{
    public partial class frmJiezhang : Form
    {
        private string opeator;
        private int num = 1;      // 就餐人数
        private string notes = "";  // 备注
        private double dPay = 0.0d;  // 实际上应该收的总金额
        public frmJiezhang(string opeator, string orderID, string strTableName)
        {
            InitializeComponent();
            this.opeator = opeator;
            this.lbl_orderID.Text = orderID;
            this.lbl_tableID.Text = strTableName;
        }

        private void Jiezhang_Load(object sender, EventArgs e)
        {
            string strOrderID = this.lbl_orderID.Text.Trim();

            if (strOrderID == "" || strOrderID.Equals(""))
            {
                MessageBox.Show("加载结帐窗体失败：订单号为空", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }
            // Load db information.
            DataAccess.OrderDAO orderDAO = new DataAccess.OrderDAO();
            DataSet ds = orderDAO.getPayingOrderInfo(strOrderID);
            if (ds == null || ! (ds.Tables[0].Rows.Count > 0))
            {
                MessageBox.Show("加载结帐窗体失败：读取数据库内容有误", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }

            DataRow dr = ds.Tables[0].Rows[0];
            if (dr != null)
            {
                this.num = Int32.Parse(dr["num"].ToString());  // 就餐人数
                this.notes = dr["notes"].ToString();  // 备注
                double totalPrice = double.Parse(dr["totalPrice"].ToString());
                double payed = double.Parse(dr["payed"].ToString());
                double dZCJE = 0;
                double dZSJE = 0;
                double dFWF = 0;
                double dMLJE = 0;
                double dYinSJE = totalPrice - dZCJE - dZSJE + dFWF - dMLJE;

                this.txt_KTSJ.Text = dr["orderTime"].ToString();  // 开台时间
                this.txt_FWY.Text = dr["waiterID"].ToString(); // 服务员
                this.txt_ZXFE.Text = this.convertMoneyToString(totalPrice);  // 总消费额
                this.txt_YiSJE.Text = this.convertMoneyToString(payed);  // 已收金额

                this.txt_ZCJE.Text = this.convertMoneyToString(dZCJE);  // 折扣金额
                this.txt_ZSJE.Text = this.convertMoneyToString(dZSJE);  // 赠送金额
                this.txt_FWF.Text = this.convertMoneyToString(dFWF);  // 服务费
                this.txt_MLJE.Text = this.convertMoneyToString(dMLJE);  // 抹零金额
                
                this.txt_YinSJE.Text = this.convertMoneyToString(dYinSJE);  // 应收金额
                this.dPay = dYinSJE - payed;
                this.txt_BCYS.Text = this.convertMoneyToString(this.dPay);  // 本次应收
            }


            SqlConnection con = DataAccess.ConnectionManager.getInstance().getConnection();
            SqlDataAdapter sda = new SqlDataAdapter("pr_getOneOrder", con);
            sda.SelectCommand.CommandType = CommandType.StoredProcedure;
            SqlParameter[] prams = {
                                       new SqlParameter("@orderID", SqlDbType.VarChar, 20)
                                   };
            prams[0].Value = this.lbl_orderID.Text.Trim();
            sda.SelectCommand.Parameters.Add(prams[0]);
            ds = new DataSet();
            sda.Fill(ds);
            DataTable dt = ds.Tables[0];

            double sumValue = 0D;      // 应收金额
            foreach (DataRow r1 in dt.Rows)
            {
                sumValue += double.Parse(r1[7].ToString()); // 折后金额
            }

            /*
            // 设计小计部分内容
            dt.Rows.Add(dt.NewRow());
            DataRow newrow = dt.NewRow();
            newrow[0] = "小计:";
            newrow[2] = "饮料";
            newrow[6] = "00.00";
            dt.Rows.Add(newrow);

            // 设计合计部分内容
            dt.Rows.Add(dt.NewRow());
            newrow = dt.NewRow();
            newrow[0] = "合计:";

            newrow[6] = string.Format("{0:.00}", ""+sumValue);

            dt.Rows.Add(newrow);

             */

            this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
            
            // 禁用所有column的单击排序事件
            foreach(DataGridViewColumn col in this.dataGridView1.Columns)
                col.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;

            // Set default config
            this.cb_paytype.SelectedIndex = 0;  // Select "现金" pay type.

        }

        private string convertMoneyToString(double money)
        {
            if (money > 0d)
                return "￥" + string.Format("{0:.00}", money) + "";
            else
                return "￥0.00";
        }

        private void txt_SKJE_TextChanged(object sender, EventArgs e)
        {
            double dPayed = 0d;
            try
            {
                if (this.txt_SKJE.Text.Trim() != "")
                    dPayed = double.Parse(this.txt_SKJE.Text.Trim());
            }
            catch(Exception e1)
            {
                Console.WriteLine(e1.Message);
            }
            this.txt_ZLJE.Text = this.convertMoneyToString(dPayed - this.dPay);
        }

        private void btn_CloseOrder_Click(object sender, EventArgs e)
        {
            string strOrderID = this.lbl_orderID.Text.Trim();
            double dPayed = (this.txt_SKJE.Text.Trim() == "") ? 0d : double.Parse(this.txt_SKJE.Text.Trim());
            if ((dPayed - this.dPay) < 0)  // 未支付足够的金额
            {
                string strShow = "对不起，未支付足够的金额，无法结帐！";
                MessageBox.Show(strShow, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            DataAccess.OrderDAO orderDAO = new DataAccess.OrderDAO();
            orderDAO.closeOrder(LoginUser.getCurrOper(), strOrderID);
            MessageBox.Show("结帐成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        // 打印帐单
        private void btn_PrintOrder_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.Rows.Count == 0)  return;
            // 建立Excel对象
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(true);
            excel.Visible = true;
            // 生成字段名称
            for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
            {
                excel.Cells[1, i + 1] = this.dataGridView1.Columns[i].HeaderText;
            }
            // 填充数据
            for (int i = 0; i < this.dataGridView1.RowCount; i++)
            {
                for (int j = 0; j < this.dataGridView1.ColumnCount; j++)
                {
                    string value = "";
                    if( this.dataGridView1[j, i].Value != null)
                    {
                        value = this.dataGridView1[j, i].Value.ToString();
                    }
                    if (this.dataGridView1[j, i].ValueType == typeof(string))
                    {
                        excel.Cells[i + 2, j + 1] = "'" + value;
                    }
                    else
                    {
                        excel.Cells[i + 2, j + 1] = value;
                    }
                }
            }
            excel = null;
            GC.Collect();
        }

        // 限制收款金额只允许输入数字
        private void txt_SKJE_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                MessageBox.Show("收款金额只允许输入数字！", "警告",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Handled = true;
            }
        }
    }
}
